package handlers

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math"
	"net/http"
	"shop/models"
	"strconv"
)

type MsgData struct {
	Sum   int `json:"sum"`
	Up    int `json:"up"`
	Down  int `json:"down"`
	Shops []models.Shop
}

func Add(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		img := c.PostForm("img")
		name := c.PostForm("name")
		number, _ := strconv.Atoi(c.PostForm("number"))
		userId, _ := strconv.Atoi(c.PostForm("user_id"))
		shop := models.Shop{
			Img:      img,
			Name:     name,
			Number:   number,
			Money:    0,
			UserId:   userId,
			BuyCount: 0,
		}
		err := db.Create(&shop).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "发布失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "发布成功",
			})
			return
		}
	}
}
func List(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
		size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
		var count int64
		db.Model(&models.Shop{}).Count(&count)
		sum := int(math.Ceil(float64(count) / float64(size)))
		up := page - 1
		if up < 1 {
			up = 1
		}
		down := page + 1
		if down > sum {
			down = sum
		}
		offset := (page - 1) * size
		var shops []models.Shop
		err := db.Joins("User").Offset(offset).Limit(size).Find(&shops).Error
		pagedata := MsgData{
			Sum:   sum,
			Up:    up,
			Down:  down,
			Shops: shops,
		}
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "分页查询失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "分页查询成功",
				"data": pagedata,
			})
		}
	}
}
func Detail(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.Query("id")
		var shop models.Shop
		err := db.Where("id=?", id).First(&shop).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "查询详情失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "查询详情成功",
				"data": shop,
			})
			return
		}
	}
}
